package com.zjhn.ds.utils;


import com.zjhn.ds.common.AuthenticationUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @BelongsProject: ds_jlw
 * @BelongsPackage: com.zjhn.ds.utils
 * @Author: sxt
 * @CreateTime: 2023-09-18  15:39
 * @Description: 登录用户工具类
 * @Version: 1.0
 */
@Component
public class UserUtil {

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    public AuthenticationUser getUserInfo() {
        // TODO
        return this.getUser(SecurityContextHolder.getContext().getAuthentication());
    }

    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    public static AuthenticationUser getUser(Authentication authentication) {
        String userName = "";
        AtomicReference<Long> userId = new AtomicReference<>(0l);
        AtomicReference<Long> tenantId = new AtomicReference<>(0l);
        AtomicReference<String> realName = new AtomicReference<>(null);
        AtomicReference<Long> department = new AtomicReference<>(0L);
        AtomicReference<String> abpUserId = new AtomicReference<>(null);
        AtomicReference<String> abpTenantId = new AtomicReference<>(null);

        if (authentication != null) {
            userName = authentication.getPrincipal().toString();

            authentication.getAuthorities().forEach(
                    item -> {
                        if (item.toString().startsWith("tenant_"))
                            tenantId.set(Long.parseLong(item.toString().replace("tenant_", "")));
                        else if (item.toString().startsWith("user_"))
                            userId.set(Long.parseLong(item.toString().replace("user_", "")));
                        else if (item.toString().startsWith("real_name_"))
                            realName.set(item.toString().replace("real_name_", ""));
                        else if (item.toString().startsWith("department_"))
                            department.set(Long.parseLong(item.toString().replace("department_", "")));
                        else if (item.toString().startsWith("abp_user_"))
                            abpUserId.set(item.toString().replace("abp_user_", ""));
                        else if (item.toString().startsWith("abp_tenant_"))
                            abpTenantId.set(item.toString().replace("abp_tenant_", ""));
                    }
            );
        }


        return new AuthenticationUser(
                userName,
                userId.get(), tenantId.get(), realName.get(), department.get(),
                abpUserId.get() == null ? null : abpUserId.get().toUpperCase() ,
                abpTenantId.get() == null ? null : abpTenantId.get().toUpperCase()
        );
    }

}
